package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func checkError(e error) {
	if e != nil {
		log.Fatal(e)
	}
}

type User struct {
	Id       int    `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

func PreQuery(db *sql.DB) {
	var u User

	// 预处理
	stmt, err := db.Prepare("select id,username,password from user where id=? or username=?")
	defer stmt.Query()
	checkError(err)

	// 查询结果集
	row, err := stmt.Query(1, "admin")
	checkError(err)

	for row.Next() {
		row.Scan(&u.Id, &u.Username, &u.Password)
		fmt.Println(u)
	}
}

func PreInsert(db *sql.DB) {

	// 预处理
	stmt, err := db.Prepare("insert  into user(username,password) values(?,?)")
	checkError(err)

	rows, err := stmt.Exec("dong", "123123")
	checkError(err)

	rowId, err := rows.LastInsertId()
	checkError(err)

	fmt.Println(rowId)
}

func main() {

	db, err := sql.Open("mysql", "root:123123@tcp(127.0.0.1:3306)/test")
	defer db.Close()
	checkError(err)

	// PreQuery(db)

	PreInsert(db)

}
